package com.zhangsun.newMvvm.base.model;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;

import com.zhangsun.newMvvm.base.bean.LoadingDialogBean;
import com.zhangsun.newMvvm.base.bean.ResponseData;
import com.zhangsun.newMvvm.base.enums.PagingLoadTypeEnum;

public abstract class BaseViewModel<T extends BaseRepository> extends AndroidViewModel {

    protected T baseRepository;

    /**
     * 用来通知 Activity／Fragment 是否显示等待Dialog
     */
    protected MutableLiveData<LoadingDialogBean> loadingDialog;

    /**
     * 当ViewModel层出现错误需要通知到Activity／Fragment
     */
    protected MutableLiveData<ResponseData> error;

    /**
     * 通知Activity／Fragment 分页的加载类型
     */
    protected MutableLiveData<PagingLoadTypeEnum> pagingLoadType;

    public BaseViewModel(@NonNull Application application, Class<T> clazz) {
        super(application);

        loadingDialog = new MutableLiveData<>();
        error = new MutableLiveData<>();
        pagingLoadType = new MutableLiveData<>();

        try {
            // 通过反射创建model的实例
            this.baseRepository = clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取等待通知
     *
     * @return 通知
     */
    public LiveData<LoadingDialogBean> getLoadingDialog() {
        return loadingDialog;
    }

    public void setDismissDialog() {
        getLoadingDialog();
        LoadingDialogBean loadingDialogBean = new LoadingDialogBean();
        loadingDialogBean.setShow(false);
        loadingDialog.setValue(loadingDialogBean);
    }

    /**
     * 获取错误通知
     *
     * @return 通知
     */
    public LiveData<ResponseData> getError() {
        return error;
    }

    /**
     * 获取加载类型通知
     *
     * @return 通知
     */
    public LiveData<PagingLoadTypeEnum> getPagingLoadType() {
        return pagingLoadType;
    }

    /**
     * ViewModel销毁同时也取消请求
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        baseRepository.dispose();
        loadingDialog = null;
        error = null;
        pagingLoadType = null;
    }

}
